import router from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css'// 进度条 style
import { getToken } from '@/utils/auth'
import { getUserMenus } from '@/api/home_'
import { filterAsyncRouter } from '@/store/modules/permission'
import MiddleUtil from '@/utils/MiddleUtil'
let allRouter = null //所有的路由
let isHomePge = '/' //用来获取默认系统首页
let sysIds = []

NProgress.configure({ showSpinner: false })
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
    document.title = Config.title
    NProgress.start()
    if (getToken()) {//已经登陆
          // 已登录且要跳转的页面是登录页
          if (to.path === '/login') {
                next()
                NProgress.done()
          } else {
                if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
                      store.dispatch('GetInfo').then((res) => { // 拉取user_info
                        loadMenus(next, to)// 动态路由，拉取菜单
                      }).catch(() => {
                        store.dispatch('LogOut').then(() => {
                          location.reload() // 为了重新实例化vue-router对象 避免bug
                        })
                      })
                } else if (store.getters.loadMenus) {// 登录时未拉取菜单，在此处拉取
                      store.dispatch('updateLoadMenus') // 修改成false，防止死循环
                      loadMenus(next, to)
                } else {
                      if(to.path=='/404'){
                        next({ path: '/dashboard', replace: true })
                      }else{
                        next()
                      }
                      NProgress.done()
                      //loadMenus(next, to)   //后来增加7-5：解决切换top菜单不更新左侧菜单
                }
          }
    } else {//未登录
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
})

function setMetaFun(v) {
  for (let i = 0; i < v.length; i++) {
    v[i].meta = {
      icon: v[i].icon,
      noCache: true,
      title: v[i].permissionName
    }
    if (v[i].children && v[i].children.length > 0) { // 父节点
      setMetaFun(v[i].children)
    } else if (sysIds.includes(v[i].parentId)&&v[i].children.length==0 && v[i].permissionName!='首页') { 
      v[i].redirect= v[i].rutePath
      v[i].children = [{
          path: v[i].rutePath,
          isShow:v[i].isShow,
          component:JSON.parse(JSON.stringify(v[i].component)),
          name: v[i].permissionName,
          meta: {
            icon: v[i].icon,
            noCache: true,
            title: v[i].permissionName
          }
        }]
      v[i].component='Layout'
    }
    v[i].path = v[i].rutePath
    v[i].name = v[i].permissionName
  }
  return JSON.parse(JSON.stringify(v))
}

function getIndexPage(v,parentPath){
  if(Array.isArray(v)&&v.length>0){
    v.forEach((item,index)=>{
      if(item.children && item.children.length>0){
        getIndexPage(item.children,item.rutePath)
      }else{
        if (item.isHomepage == 1) { //超过两层的菜单设置默认首页会有问题
          if(!parentPath){
            isHomePge = item.rutePath
          }else{
            isHomePge = parentPath+'/'+item.rutePath
          }
        }
      }
    })
  }
}

export const loadMenus = (next, to) => {
  getUserMenus().then(routerRes => {
      const routerList = JSON.parse(JSON.stringify(routerRes.data)) // 不用自己过滤了
      sysIds = []
      routerList.forEach((item,index)=>{sysIds.push(item.id)})
      sessionStorage.setItem('routerListNav', JSON.stringify(routerList))//保存过滤后的菜单，给系统的tab渲染，切换系统
      const res1 =  setMetaFun(routerList) //重置路由结构

      allRouter = res1
      let getsysObj = sessionStorage.getItem('sysObj')?JSON.parse(sessionStorage.getItem('sysObj')):"" //浏览器中已经切换过系统，保存有系统的名称
      if(getsysObj){refreshSetRouter(getsysObj,next,to)}else{
      let res = []
      const routerList2 = JSON.parse(JSON.stringify(res1)) //复制一份
      let delIndex = []
      res1.forEach((item, index) => {
        if (item.isShow == 1) { //先手动删除不显示的【系统】
          delIndex.push(index)
        }
      })
      let filterrouterList = routerList2.filter((item,index)=>{
        return !delIndex.includes(index)
      })
      res = filterrouterList[0].children//解决菜单默认是顶部tab第一个的
      getIndexPage(res,null) //获得默认系统首页
      sessionStorage.setItem('filtersrouterListNav', JSON.stringify(filterrouterList))//保存过滤后的菜单，给系统的tab渲染，切换系统
      sessionStorage.setItem('sysType', filterrouterList[0].id)
      const sdata = JSON.parse(JSON.stringify(res))
      const rdata = JSON.parse(JSON.stringify(res))
      const sidebarRoutes = filterAsyncRouter(sdata)
      const rewriteRoutes = filterAsyncRouter(rdata, false, true)
      rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
      rewriteRoutes.forEach((item, index) => {
        router.addRoute(item)
      })
      // next({ ...to, replace: true })
      next({path:isHomePge, replace: true })
      store.dispatch('SetSidebarRouters', sidebarRoutes) //左侧菜单渲染
    }
    next()
  })
}



MiddleUtil.$on('changeInfoList', (v,callBack) => {
  refreshSetRouter(v.parm,'','',callBack)
})

function refreshSetRouter(v, next, to,callBack) {
  let list = null
  for (let i = 0; i < allRouter.length; i++) {
    if (allRouter[i].id == v.id) {
      list = allRouter[i].children
    }
  }
  const sdata = JSON.parse(JSON.stringify(list))
  const rdata = JSON.parse(JSON.stringify(list))
  const sidebarRoutes = filterAsyncRouter(list)
  const rewriteRoutes = filterAsyncRouter(rdata, false, true)
 
  store.dispatch('SetSidebarRouters', sidebarRoutes)

  rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
  setTimeout(()=>{
    rewriteRoutes.forEach((item, index) => {
      router.addRoute(item)
    })
    if(callBack){
      callBack() //解决顶部菜单点击两次的问题，所以放到点击后菜单加载进来后再跳转
    }
  },300)
}
//页面刷新
router.afterEach(() => {
  NProgress.done()
})
